import React, { useState, useEffect } from 'react';
import { 
  Container, 
  Grid, 
  CssBaseline, 
  Paper,
  Tabs,
  Tab,
  Box,
  Button,
  Snackbar,
  Alert
} from '@mui/material';
import { Link, useLocation } from 'react-router-dom';
import Navbar from '../components/Navbar';
import HotVideo from '../components/HotVideo';
import ImageSlider from '../components/Imagelider';
import Recommend from '../components/Recommend';
import PreferenceModal from '../components/Selectlike';
import { navigationItems } from '../App';

function Main() {
  const location = useLocation();
  const [user, setUser] = useState(null);
  const [openSnackbar, setOpenSnackbar] = useState(false);
  
  useEffect(() => {
    // 从 localStorage 获取用户信息
    const userToken = localStorage.getItem('token');
    if (userToken) {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user'));
        setUser(userInfo);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    }
  }, []);

  // 设置用户为管理员
  const handleSetAdmin = () => {
    try {
      let userInfo = user;
      
      // 如果用户不存在，创建一个基本用户对象
      if (!userInfo) {
        userInfo = {
          username: '测试管理员',
          avatar: '/default/avatar.png'
        };
      }
      
      // 设置管理员角色
      userInfo.role = 'admin';
      
      // 更新本地存储
      localStorage.setItem('user', JSON.stringify(userInfo));
      
      // 更新状态
      setUser(userInfo);
      
      // 显示成功消息
      setOpenSnackbar(true);
      
      // 刷新页面以更新导航菜单
      setTimeout(() => {
        window.location.reload();
      }, 1500);
    } catch (error) {
      console.error('设置管理员失败:', error);
    }
  };
  
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    const isFirstTime = localStorage.getItem("first_time") !== "false";
    if (isFirstTime) {
      setShowModal(true);
    }
  }, []);

  const closeModal = () => {
    localStorage.setItem("first_time", "false");
    setShowModal(false);
  };
  return (
<div className="App" style={{ backgroundColor: '#fefaff', minHeight: '100vh' }}>
      <CssBaseline />
      <Navbar />
            <PreferenceModal show={showModal} onClose={closeModal} />

      <Container
        maxWidth="false"
        sx={{
          backdropFilter: 'blur(4px)',
          backgroundColor: 'rgba(255,255,255,0.6)',
          borderRadius: 3,
          p: 2,
          mt: 3,
        }}
      >

      <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
        <Tabs
            value={location.pathname}
            indicatorColor="secondary"
            textColor="secondary"
            variant="scrollable"
            scrollButtons="auto"
            sx={{
              borderBottom: '2px solid #f3e5f5',
              mb: 2,
              '& .MuiTab-root': {
                transition: 'all 0.3s ease-in-out',
              },
              '& .Mui-selected': {
                color: '#8e24aa',
                fontWeight: 'bold',
              },
              '& .MuiTabs-indicator': {
                height: 3,
                backgroundColor: '#ce93d8',
                borderRadius: 2,
              }
            }}
          >

          {navigationItems
            .filter(item => !item.adminOnly || (user && user.role === 'admin'))
            .map((item) => (
            <Tab
              key={item.path}
              label={item.label}
              value={item.path}
              component={Link}
              to={item.path}
              sx={{
                minWidth: 100,
                borderRadius: 2,
                mx: 0.5,
                transition: 'all 0.3s',
                color: '#8e24aa',
                '&:hover': {
                  backgroundColor: '#ffe0f0',
                  color: '#d81b60',
                },
                '&.Mui-selected': {
                  fontWeight: 'bold',
                  color: '#d81b60',
                  backgroundColor: '#fff0f5',
                },
              }}
            />
          ))}
        </Tabs>
        </Box>
      </Container>

      <Container maxWidth="false" sx={{ paddingTop: 3 }}>
      <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
        {/* 测试用按钮 */}
        <Box sx={{ mb: 2, display: 'flex', justifyContent: 'flex-end' }}>
          <Button 
            variant="contained" 
            color="warning" 
            onClick={handleSetAdmin}
            sx={{ mb: 1 }}
          >
            测试：设置为管理员
          </Button>
        </Box>

        <Paper elevation={3} sx={{
            p: 2,
            mb: 3,
            borderRadius: 3,
            background: 'linear-gradient(135deg, #fff0f5 0%, #fce4ec 100%)',
            boxShadow: '0 4px 20px rgba(200, 100, 255, 0.1)',
          }}>

          <Grid container spacing={3}>
            <Grid item xs={12} md sx={{ flex: '2 0 0%' }}>
              <ImageSlider />
            </Grid>
            <Grid item xs={12} md sx={{ flex: '3 0 0%' }}>
              <Recommend />
            </Grid>
          </Grid>
        </Paper>

        <Paper elevation={3} sx={{
  p: 2,
  borderRadius: 3,
  background: 'linear-gradient(135deg, #e0f7fa 0%, #e6f7ff 100%)',
  boxShadow: '0 4px 20px rgba(100, 100, 255, 0.1)',
}}>
          <HotVideo />
        </Paper>
        </Box>
      </Container>
      
      {/* 提示消息 */}
      <Snackbar 
        open={openSnackbar} 
        autoHideDuration={3000} 
        onClose={() => setOpenSnackbar(false)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert onClose={() => setOpenSnackbar(false)} severity="success" sx={{ width: '100%' }}>
          已成功设置为管理员，页面将自动刷新！
        </Alert>
      </Snackbar>
    </div>
  );
}
export default Main;